<?php

namespace app\api\controller;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use Darabonba\OpenApi\Models\Config;
use think\Request;

class Msg extends Base
{
    // 是否自动实例化当前模型
    protected $autoNewModel = false;
    // 是否开启自动验证
    protected $autoValidateCheck = false;

    public function sendCode(Request $request)
    {
//        $CacheClass = \think\facade\Cache::store(config('cms.user.token.store'));
//        $a = $CacheClass->get('mobile_18028432514');var_dump($a);
//        die;
        $accessKeyId = 'LTAI5tJCoGpSkhvtjcMLfgAh';
        $accessKeySecret = 'K3fqdKpJ0hfKa0c9XtAfXa9GgPoDez';
        //接收手机号参数
//        $phone = $request->post('phone');echo $phone;die;
        $phone = input('mobile');//echo $phone;die;
//        $yzm = input('yzm');
//        $phone = $request->get('phone');echo $phone;die;
        //这个是验证码
        $code = ['code' => rand(1111, 9999)];

        //发短信
        $client = self::createClient($accessKeyId, $accessKeySecret);//var_dump($client);die;
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => "民尚优品",
            "templateCode" => "SMS_269065741",
            "templateParam" => json_encode($code)
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $data = $client->sendSms($sendSmsRequest);

        $arr = (array)$data;
        $body = (array)$arr['body'];
        // var_dump($body['message'] == 'OK');
        if($body['message'] == 'OK'){
            $CacheClass = \think\facade\Cache::store(config('cms.user.token.store'));
            $CacheClass->set('mobile_' . $phone, $code, 300);
            return showSuccess('已发送', '已发送');

        }else{
            return showError($body['message']);
        }
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

}